/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sessions;

import entities.Notification;
import entities.NotificationType;
import entities.UUser;
import init.Config;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author Antoine Boulinguez et Shyn-Yuan Cheng
 */
@Stateless
@LocalBean
public class NotificationManager {
    @PersistenceContext(unitName = "ProjetStreamingBoulinguezCheng-ejbPU")
    private EntityManager em;
    
    
    public Notification createNotification(String description, NotificationType type, UUser userFrom, UUser userTo) {
        // Get today date
        Calendar cal = Calendar.getInstance();
        Date date = cal.getTime();
        
        // Create notification
        Notification notification = new Notification(date, description, type, userFrom, userTo);
        persist(notification);
        
        userTo.addNotification(notification);
        update(userTo);
        
        return notification;
    }
    
     // Get notifications
    public List<Notification> getNotifications(UUser toUser) {
        Query query = em.createNamedQuery("Notification.findByReceiver");
        query.setParameter("toUser", toUser);
        
        return query.getResultList();
    }
    
    // Get notification description for a new friend event
    public String getFriendNotificationDescription(UUser userFrom) {
        return userFrom.getFirstname() + " " + userFrom.getLastname() + " " + Config.NEW_FRIEND_NOTIFICATION_MESSAGE;
    }
    
    // Get notification description for a new shared playlist event
    public String getPlaylistNotificationDescription(UUser userFrom, String title) {
        return userFrom.getFirstname() + " " + userFrom.getLastname() + " " + Config.SHARE_PLAYLIST_NOTIFICATION_MESSAGE + " " + title + ".";
    }
    
    public void update(Object object) {
        em.merge(object);
    }

    public void persist(Object object) {
        em.persist(object);
    }
}
